Fractions in bash/shell terminal
Created | |
---|---|
Tags | bashshell |
Math using bash variables is not straight forward and I always end up forgetting the rules, so I am outlining them here with examples.
Division
I needed to calculate how much of an overlap there was between my bed file of approximated enhancers in the mouse genome in a specific cell type and the mm10 enhancer list from Fantom5.
So first I used bedtools2 to get the intersection and wc -l
to get the raw numbers.
# get intersection
bedtools intersect -a F5.mm10.enhancers.bed -b P7_enhancers.bed > overlap.bed
# save wc -l output to variable for the overlap
# this will be my numerator
OVERLAP=($(wc -l P7_overlap.bed ))
echo $OVERLAP
4238
# save wc -l output to variable for the enhancer set
# this is be my denominator
TOTAL=($(wc -l F5.mm10.enhancers.bed ))
echo $TOTAL
49797
Then simply divide the number of lines from the intersection and number of lines in the enhancer list.
echo $$(OVERLAP / TOTAL))
0
But the since this division will result in a number less than 0 bc
must be used
echo "scale=2 ; $OVERLAP / $TOTAL" | bc
.08
To save this output to a variable
OUTPUT=($( echo "scale=2 ; $OVERLAP / $TOTAL" | bc ))
echo $OUTPUT
.08
Note : there are other was to compute this in a way that return a float.
bc <<<"scale=2; $OVERLAP / $TOTAL"
awk -v A="$OVERLAP" -v B="$TOTAL" 'BEGIN { print A / B }'